import React, { useState } from 'react';
import {
  Form,
  Input,
  Button,
  Modal,
  Descriptions,
  Radio,
  Select,
  Popconfirm,
  InputNumber,
  DatePicker,
  Space,
} from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import columnsData, { columnsDataType } from './data';
import TableTitle from '../../../components/TableTitle';
import { PlusOutlined } from '@ant-design/icons';
import {
  getTaskPageList,
  createTask,
  publishTask,
  auditTask,
  getTaskDetails,
  getAccountCategoryByCustomerNo,
} from './service';
import { getLocalStorageInfo } from '@/utils/localStorageInfo';

const { RangePicker } = DatePicker;

export default () => {
  const { Option } = Select;
  const { TextArea } = Input;
  let customerInfo = getLocalStorageInfo('customerInfo');
  console.log('customerInfo.customerNo', customerInfo.customerNo);
  // 控制新增模态框
  const [isAddTaskModal, setIsAddTaskModal] = useState(false);
  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData;
  // 控制查看模态框
  const [isViewTaskModal, setIsViewTaskModal] = useState(false);
  // 控制发布模态框
  const [isPublishTaskModal, setIsPublishTaskModal] = useState(false);
  // 控制审核模态框
  const [isAuditTaskModal, setIsAuditTaskModal] = useState(false);
  // 存储用户信息
  const [isViewDetailsData, setIsViewDetailsData] = useState({});
  // 币种信息
  const [isccy, setIsccy] = useState([]);
  // 账户类型信息
  const [accountCategory, setAccountCategory] = useState([]);
  // 存储任务编号
  const [isSerialNo, setisSerialNo] = useState({});
  // 存储回显的意见
  const [isSubmitContent, setIsSubmitContent] = useState('');
  // 获取表单
  const [FormRef] = Form.useForm();

  // 任务起止时间
  const [taskStartTime, setTaskStartTime] = useState('');
  const [taskEndTime, setTaskEndTime] = useState('');

  // 发布表单
  const [pubulishFormRef] = Form.useForm();

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      <li>
        <a
          onClick={() => {
            toViewTaskDetail(record);
          }}
        >
          查看
        </a>
      </li>
      {record.status == 0 ? (
        <li
          onClick={() => {
            toPublishTask(record);
          }}
        >
          <a>发布</a>
        </li>
      ) : null}
      {record.status == 3 ? (
        <li
          onClick={() => {
            toAuditTask(record);
          }}
        >
          <a>审核</a>
        </li>
      ) : null}
    </ul>
  );

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  // Table action 的引用，便于自定义触发
  const actionRef = React.useRef<ActionType>();

  /**
   * 新增任务
   */
  const increaseTask = () => {
    getAccountCategoryByCustomerNo({
      customerNo: customerInfo.customerNo,
    }).then((res) => {
      let resultArr = res.data;
      // 数组去重,获得币种
      let newResultArr = [...new Set(resultArr)];
      console.log('newResultArr🎉', newResultArr);
      setIsccy(newResultArr);
    });
    setIsAddTaskModal(true);
  };

  const confirmAddTask = () => {
    // 获取输入的表单值
    FormRef.validateFields()
      .then(async () => {
        let response = FormRef.getFieldsValue();
        response.startTime = taskStartTime;
        response.endTime = taskEndTime;
        // 表明平台任务
        response.type = 1;
        // 客户编号
        response.customerNo = customerInfo.customerNo;
        // 新增任务接口
        let addRes = await createTask(response);
        console.log('addRes', addRes);
        // 重置输入的表单
        FormRef.resetFields();
        // 刷新proTable
        actionRef.current?.reload();
        setIsAddTaskModal(false);
      })
      .catch(() => {});
  };
  const cancelAddTask = () => {
    setIsAddTaskModal(false);
  };

  /**
   * 发布任务
   */
  const toPublishTask = async (record) => {
    setIsPublishTaskModal(true);
    getAccountCategoryByCustomerNo({
      customerNo: customerInfo.customerNo,
    }).then((res) => {
      let resultArr = res.data;
      setAccountCategory(resultArr);
      // 数组去重,获得币种
      console.log('resultArr', resultArr);
    });
    let { serialNo } = record;
    setisSerialNo(serialNo);
  };

  // 确定发布任务
  const confirmPublishTask = async () => {
    pubulishFormRef.validateFields().then(async () => {
      let response = pubulishFormRef.getFieldsValue();
      response.serialNo = isSerialNo;
      let publishRes = await publishTask(response);
      console.log('publishRes', publishRes);
      if (publishRes.code === '000000') {
        setIsPublishTaskModal(false);
        // 刷新proTable
        actionRef.current?.reload();
      }
    });
  };

  // 取消发布任务
  const cancelPublishTask = () => {
    setIsPublishTaskModal(false);
  };

  // 审核任务
  const toAuditTask = async (record) => {
    console.log('record', record);
    setIsAuditTaskModal(true);
    let serialNo = record.serialNo;
    let submitContent = record.submitContent;
    console.log(submitContent);
    console.log(record);
    // 存储serialNo
    setisSerialNo(serialNo);
    // 存储回显意见
    setIsSubmitContent(submitContent);
  };

  // 确定审核任务
  const confirmAuditTask = () => {
    FormRef.validateFields().then(async () => {
      let response = FormRef.getFieldsValue();
      response.serialNo = isSerialNo;
      console.log('response', response);
      let auditRes = await auditTask(response);
      if (auditRes.code === '000000') {
        setIsAuditTaskModal(false);
        // 刷新proTable
        actionRef.current?.reload();
      }
    });
  };

  // 取消审核任务
  const cancelAuditTask = () => {
    setIsAuditTaskModal(false);
  };

  const setTaskTime = (moment, dateString) => {
    setTaskStartTime(dateString[0]);
    setTaskEndTime(dateString[1]);
  };

  // 查看任务详情
  const toViewTaskDetail = async (record) => {
    // console.log(record)
    let { serialNo } = record;
    let detailsRes = await getTaskDetails({ serialNo });
    console.log('detailsRes', detailsRes);
    setIsViewDetailsData(detailsRes.data);
    setIsViewTaskModal(true);
  };

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<TableTitle title="任务管理" />}
        scroll={{ x: 900 }}
        actionRef={actionRef}
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={async (params) => {
          console.log(params);
          let res = await getTaskPageList({
            ...params,
            customerNo: customerInfo.customerNo,
          });
          console.log('😒', res);
          const result = {
            data: res.data,
            total: res.pagination.totalSize,
          };
          return result;
        }}
        rowKey="serialNo"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Button
            onClick={() => {
              increaseTask();
            }}
            key="button"
            icon={<PlusOutlined />}
            type="primary"
          >
            新增
          </Button>,
        ]}
      />
      {/* 新增任务模态框 */}
      <Modal
        title="新增任务"
        visible={isAddTaskModal}
        onOk={confirmAddTask}
        onCancel={cancelAddTask}
        centered
      >
        <Form
          name="basic"
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 14 }}
          initialValues={{ claimMethod: 0 }}
          form={FormRef}
        >
          <Form.Item
            label="任务名称"
            name="taskName"
            rules={[{ required: true, message: '请输入任务名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="任务类型"
            name="claimMethod"
            rules={[{ required: true, message: '请选择任务类型!' }]}
          >
            <Radio.Group>
              <Radio value={0}>单人任务</Radio>
              <Radio value={1}>多人任务</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="出资账户"
            name="category"
            rules={[{ required: true, message: '请选择出资账户!' }]}
          >
            <Select>
              {isccy.map((item, index) => {
                return (
                  <Option value={item.category} key={index}>
                    {item.name}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="激励金额"
            name="incentiveAmount"
            rules={[{ required: true, message: '请输入激励金额' }]}
          >
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="任务起止日期">
            <RangePicker onChange={setTaskTime} />
          </Form.Item>

          <Form.Item
            label="任务描述"
            name="description"
            rules={[{ required: true, message: '请输入任务描述' }]}
          >
            <TextArea placeholder="请输入任务描述" />
          </Form.Item>
        </Form>
      </Modal>
      {/* 查看详情模态框 */}
      <Modal
        title="任务详情"
        width={900}
        centered
        visible={isViewTaskModal}
        onOk={() => setIsViewTaskModal(false)}
        onCancel={() => setIsViewTaskModal(false)}
      >
        {/* 详情信息 */}
        <Descriptions title="任务详情">
          <Descriptions.Item label="任务标题">
            {isViewDetailsData.taskName}
          </Descriptions.Item>
          <Descriptions.Item label="任务编号">
            {isViewDetailsData?.serialNo}
          </Descriptions.Item>
          <Descriptions.Item label="发布人">
            {isViewDetailsData?.createBy}
          </Descriptions.Item>
          <Descriptions.Item label="发布时间">
            {isViewDetailsData?.createTime}
          </Descriptions.Item>
          <Descriptions.Item label="激励金额">
            {isViewDetailsData?.incentiveAmount}
          </Descriptions.Item>
          <Descriptions.Item label="描述信息">
            {isViewDetailsData?.description}
          </Descriptions.Item>
        </Descriptions>
      </Modal>
      {/* 发布模态框 */}
      <Modal
        title="发布任务"
        visible={isPublishTaskModal}
        onOk={confirmPublishTask}
        onCancel={cancelPublishTask}
        centered
      >
        <Form
          name="basic"
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 14 }}
          form={pubulishFormRef}
        >
          <p>确定发布该任务？</p>
        </Form>
      </Modal>
      {/* 审核模态框 */}
      {/* 发布模态框 */}
      <Modal
        title="审核任务"
        visible={isAuditTaskModal}
        onOk={confirmAuditTask}
        onCancel={cancelAuditTask}
        centered
      >
        <Form
          name="basic"
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 14 }}
          form={FormRef}
          initialValues={{ auditStatus: '0' }}
        >
          <Form.Item label="提交反馈" name="submitContent">
            <TextArea defaultValue={isSubmitContent} disabled />
          </Form.Item>
          <Form.Item
            label="任务状态"
            name="auditStatus"
            rules={[{ required: true, message: '请选择任务状态' }]}
          >
            <Radio.Group>
              <Radio value={'0'}>通过</Radio>
              <Radio value={'1'}>驳回</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="审核意见"
            name="remark"
            rules={[{ required: true, message: '请输入审核意见' }]}
          >
            <TextArea placeholder="请输入审核意见" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
